<template>
  <div class="content">
    <uni-popup ref="popup" type="bottom" @maskClick="closeHandler">
      <view class="batch-processing-box">
        <view class="top-height"></view>
        <view class="switch-box">
          <view class="switch-item-box">
            <switch :checked="isEdit" color="#f0ad4e" @change="editSwitch" />
            <span>编辑模式</span>
          </view>
          <view class="switch-item-box">
            <switch :checked="isDeleteCommand" color="#dd524d" @change="deleteCommandSwitch" />
            <span>删除模式</span>
          </view>
          <view class="switch-item-box">
            <switch :checked="isExport" color="#007aff" @change="exportCommandSwitch" />
            <span>导出模式</span>
          </view>
        </view>

        <button class="base-button out-btn" @click="exportCommand" v-if="isExport">导出</button>
        <button class="func-button out-btn" :disabled="isEdit || isDeleteCommand" @click="importCommand" v-else>导入</button>

        <scroll-view class="scroll-view" scroll-y="true">
          <view class="btn-group">
            <button @click="btnClickHandler('TurnOff')" :disabled="isEdit || isDeleteCommand || isExport" class="base-button btn">立即关机</button>
            <button @click="btnClickHandler('Restart')" :disabled="isEdit || isDeleteCommand || isExport" class="base-button btn">立即重启</button>
            <button @click="btnClickHandler('LockOn')" :disabled="isEdit || isDeleteCommand || isExport" class="base-button btn">立即锁定</button>
            <button @click="btnClickHandler('ScreenOff')" :disabled="isEdit || isDeleteCommand || isExport" class="base-button btn">立即息屏</button>
            <button @click="clickBtnHandler(command_btn)" class="base-button btn" :class="btnStyle(command_btn)" v-for="command_btn in commandList" :key="command_btn.command">{{ command_btn.name }}</button>
            <!-- 自定义命令按钮 -->
            <button v-if="!isEdit && !isDeleteCommand && !isExport" @click="openAddCommand" class="func-button btn">
              <uni-icons type="plusempty" size="20" color="#2979ff"></uni-icons>
              自定义命令
            </button>
          </view>
        </scroll-view>
        <view class="delete-fab-btn" :class="selectCommandList.length && isDeleteCommand ? 'fabBtnAnimation' : 'fabBtnAnimation_reverse'" @click="deleteCommand">
          <uni-icons type="trash-filled" size="35" color="#ffffff"></uni-icons>
        </view>
      </view>
    </uni-popup>

    <!-- 顶部通知 -->
    <top-notification ref="topNotificationRef" />
    <!-- 自定义命令添加表单 -->
    <command-form ref="commandFormRef" />
    <!-- 导入导出窗口组件 -->
    <import-export ref="importExportRef" />
  </div>
</template>

<script setup>
import { turnOffCommand, restartCommand, lockOnCommand, screenOffCommand, sendCustomCommand, sendCustomScript } from "@/api/control.js";
import { ref, watch } from "vue";
import useComputerStore from "@/store/modules/computer.js";
import { storeToRefs } from "pinia";
import importExport from "@/pages/detail/components/importExport";
import { isAuthPass } from "../../../utils/authentication";
// 节流阀
let isLoading = ref(false);

const throttle = async (func) => {
  if (isLoading.value) return;
  isLoading.value = true;
  uni.showLoading({
    title: "请求执行中",
    mask: true,
  });
  // #ifdef APP-PLUS
  uni.vibrateShort();
  // #endif

  await func();
  isLoading.value = false;
  uni.hideLoading();
};
const computerStore = useComputerStore();
const { commandList } = storeToRefs(computerStore);

const props = defineProps({
  batchProcessingArray: Array,
});

// 顶部提示横幅实例
const topNotificationRef = ref();

// 批量操作弹窗实例
const popup = ref();

// 开启弹窗
const open = () => {
  popup.value.open("right");
};

//关闭弹窗
const close = () => {
  popup.value.close();
};

let failedList = ref([]);

const btnClickHandler = (type, customCommand) => {
  throttle(async () => {
    failedList.value = [];
    let msg = "";
    for (let i = 0; i < props.batchProcessingArray.length; i++) {
      let item = props.batchProcessingArray[i];
      let res = {};

      if (type === "TurnOff") {
        msg = "关机";
        res = await turnOffCommand(item);
      } else if (type === "Restart") {
        msg = "重启";
        res = await restartCommand(item);
      } else if (type === "LockOn") {
        msg = "锁定";
        res = await lockOnCommand(item);
      } else if (type === "ScreenOff") {
        msg = "息屏";
        res = await screenOffCommand(item);
      } else {
        msg = customCommand.name;
        if (customCommand.script_type === "cmd") {
          res = await sendCustomCommand(item, customCommand);
        } else {
          res = await sendCustomScript(item, customCommand);
        }
      }
      if (res.code !== 200) failedList.value.push(item);
    }
    emit("failedEvent", failedList.value);
    close();
    closeHandler();
    if (failedList.value.length) {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: `已发送【${msg}】指令，部分设备执行失败`,
      });
    } else {
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: `已批量发送【${msg}】指令`,
      });
    }
  });
};

const emit = defineEmits(["closeEvent", "failedEvent"]);

const closeHandler = (func) => {
  emit("closeEvent");
};

// 命令窗口
const commandFormRef = ref();

// 打开添加命令窗口
const openAddCommand = () => {
  commandFormRef.value.openAddCommand();
};

// 修改命令
const isEdit = ref(false);

// 修改命令切换
const editSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isEdit.value = e.detail.value;
  if (isEdit.value) {
    if (isDeleteCommand.value) isDeleteCommand.value = !isDeleteCommand.value;
    if (isExport.value) isExport.value = !isExport.value;
  }
};

// 修改命令
const editCommand = (custom_command) => {
  commandFormRef.value.openAddCommand(custom_command);
};

//按钮命令点击事件
const clickBtnHandler = (command_btn) => {
  if (isEdit.value) {
    editCommand(command_btn);
  } else if (isDeleteCommand.value) {
    chooseCommand(command_btn);
  } else if (isExport.value) {
    chooseCommand(command_btn);
  } else {
    btnClickHandler("CustomCommand", command_btn);
  }
};

// 是否批量删除
let isDeleteCommand = ref(false);

watch(
  () => isDeleteCommand.value,
  (newVal) => {
    if (!newVal) selectCommandList.value = [];
  }
);

// 删除的命令数组
let selectCommandList = ref([]);

// 批量删除切换
const deleteCommandSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isDeleteCommand.value = e.detail.value;
  if (isDeleteCommand.value) {
    if (isEdit.value) isEdit.value = !isEdit.value;
    if (isExport.value) isExport.value = !isExport.value;
  }
};

// 选择需要批量删除的命令
const chooseCommand = (custom_command) => {
  let index = selectCommandList.value.indexOf(custom_command);
  if (index === -1) {
    selectCommandList.value.push(custom_command);
  } else {
    selectCommandList.value.splice(index, 1);
  }
};

// 批量删除
const deleteCommand = () => {
  if (isAuthPass()) return;
  let filterCommand = commandList.value.filter((item) => {
    if (!selectCommandList.value.includes(item)) {
      return item;
    }
  });
  computerStore.updateCommandList(filterCommand);
};

// 导出模式
let isExport = ref(false);

watch(
  () => isExport.value,
  (newV) => {
    if (!newV) selectCommandList.value = [];
  }
);

// 导出模式切换
const exportCommandSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isExport.value = e.detail.value;
  if (isExport.value) {
    if (isEdit.value) isEdit.value = !isEdit.value;
    if (isDeleteCommand.value) isDeleteCommand.value = !isDeleteCommand.value;
  }
};

// 导入导出组件实例
const importExportRef = ref();
// 自定义命令导入
const importCommand = () => {
  importExportRef.value.openInputDialog();
};
// 自定义命令导出
const exportCommand = () => {
  importExportRef.value.openAlertDialog(selectCommandList.value);
};

// 不同状态下的按钮
const btnStyle = (custom) => {
  let style = [];
  if (selectCommandList.value.includes(custom)) {
    if (isDeleteCommand.value) style.push("delete-shadow");
    if (isExport.value) style.push("export-shadow");
  }
  if (custom.permission) {
    style.push("warning-button");
  } else {
    style.push("base-button");
  }

  return style.join(" ");
};

defineExpose({ open, close, closeHandler });
</script>

<style lang="scss" scoped>
.batch-processing-box {
  padding: 20px 0 env(safe-area-inset-bottom) 0;
  box-sizing: border-box;
  width: 250px;
  height: 100vh;
  background-color: #fff;
  position: relative;
  .top-height {
    height: var(--status-bar-height);
  }
  .switch-box {
    width: 230px;
    margin-left: 10px;
    height: 140rpx;
    background-color: #f7f8fb;
    border-radius: 10px;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .switch-item-box {
      display: flex;
      flex-direction: column;
      align-items: center;
      span {
        margin-top: 5px;
        font-size: 9px;
        color: #3f3f3f83;
      }
    }
  }
  .out-btn {
    width: 230px;
    margin-left: 10px;
    height: 35px;
    line-height: 35px;
  }
  .scroll-view {
    height: calc(100% - 230rpx - 35px);
    padding: 10px;
    box-sizing: border-box;
    .btn-group {
      display: flex;
      flex-direction: column;
      .btn {
        margin-bottom: 20rpx;
        width: 100%;
      }
    }
    .delete-shadow {
      border: 2px solid #dd524d;
      box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(222, 81, 77, 0.5);
      color: #b82e29a2;
    }

    .export-shadow {
      border: 2px solid #007aff;
      box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(0, 123, 255, 0.5);
      color: #15406e83;
    }
  }
  .delete-fab-btn {
    background-color: #dd524d;
    width: 90rpx;
    height: 90rpx;
    position: absolute;
    bottom: 90rpx;
    right: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50rpx;
    box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(222, 81, 77, 0.4);
  }
}
</style>
